package persistence.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import persistence.db.DataSet;
import persistence.db.DatabaseConnector;
import persistence.model.AbstractModel;
import persistence.model.Matiere;
import persistence.model.UE;

public class UEDAO extends AbstractDAO{
	
	private UE ue;
	
	/**
	 * Constructeur d'une UE DAO
	 */
	public UEDAO() {
		setTableName("UE");
	}

	/**
	 * Constructeur d'une UE DAO
	 * @param ue ue correspondante
	 */
	public UEDAO(UE ue){
		this();
		this.ue = ue;
		setId(ue.getId());
	}
	
	public DataSet all() {
		return new DataSet(this);
	}

	public AbstractModel makeModel(ResultSet rset) {
		try {
			setId(
					rset.getInt("id_UE"));
			
			DataSet matiereSet = Matiere.all().filter("FK_MATIERE_UE = " + getId());
			
			return new UE(getId(),
					rset.getString("nomUE"),
					rset.getString("descriptionUE"),
					rset.getInt("nbECTS"),
					rset.getInt("noteMinimaleUE"),
					rset.getInt("FK_UE_SEMESTRE"),
					matiereSet);
		} catch (SQLException e) {
			System.out.println("makeModel error");
			e.printStackTrace();
		}
		return null;
	}

	public void save() {
		String query;
		ResultSet result;
			query = "INSERT INTO " + getTableName() + " VALUES ( S_PK_"+ getTableName() +".nextval, '" +
			ue.getNomUE() + "', '" +
			ue.getDescriptionUE() + "', "+
			ue.getNbECTS() + ", " +
			ue.getNoteMinUE() + ", " +
			ue.getIdSemestre()+ ")";
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
			setId(this.getId()); /* Mise a jour de l'identifiant */
	}

	public void save(int id) {
		String query;
		ResultSet result;
			query = "UPDATE " + getTableName() +
				" SET nomUE = '" + ue.getNomUE() +
				"', descriptionUE = '" + ue.getDescriptionUE() +
				"', nbects = " + ue.getNbECTS() +
				", noteminimaleue = " + ue.getNoteMinUE() +
				", fk_ue_semestre = " + ue.getIdSemestre() +
				" WHERE ID_"+ getTableName() + " = " + id;
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
	}
}
